import { NextResponse } from "next/server";
import { getUser } from '@/lib/authUtils';
import { checkStorageLimit, updateStorageUsage } from '@/lib/limitChecker';
const COS = require('cos-nodejs-sdk-v5');

const cos = new COS({
  SecretId: process.env.TENCENT_SECRET_ID,
  SecretKey: process.env.TENCENT_SECRET_KEY,
});

export async function POST(req: Request) {
  if (!process.env.TENCENT_SECRET_ID || !process.env.TENCENT_SECRET_KEY) {
    return new Response("Missing COS credentials. Please add SecretId and SecretKey to your .env file.", {
      status: 401,
    });
  }

  // 验证用户身份
  const userId = await getUser(req);
  if (!userId) {
    return NextResponse.json({ error: '未授权访问' }, { status: 401 });
  }
  if (userId instanceof NextResponse) {
    return userId;
  }

  const file = await req.arrayBuffer();
  const filename = req.headers.get("x-vercel-filename") || "file.txt";
  const contentType = req.headers.get("content-type") || "text/plain";
  const fileType = `.${contentType.split("/")[1]}`;
  const finalName = filename.includes(fileType) ? filename : `${filename}${fileType}`;
  const timestamp = Date.now();
  const uniqueKey = `img/${timestamp}_${finalName}`;
  
  const fileSizeBytes = file.byteLength;

  try {
    // 检查存储限制
    const storageCheck = await checkStorageLimit(userId, fileSizeBytes);
    if (!storageCheck.allowed) {
      return NextResponse.json({
        error: '存储空间不足',
        details: {
          currentUsage: storageCheck.currentUsage,
          limit: storageCheck.limit,
          planType: storageCheck.planType,
          fileSize: Math.ceil(fileSizeBytes / (1024 * 1024))
        }
      }, { status: 413 }); // 413 Payload Too Large
    }

    const result = await new Promise<any>((resolve, reject) => {
      cos.putObject({
        Bucket: process.env.TENCENT_COS_BUCKET,
        Region: process.env.TENCENT_COS_REGION,
        Key: uniqueKey,
        Body: Buffer.from(file),
        ContentType: contentType,
      }, function(err: Error, data: any) {
        if (err) {
          console.error('COS upload error:', err);
          reject(err);
        } else {
          console.log('COS upload success:', data);
          resolve(data);
        }
      });
    });

    // 上传成功后更新用户存储使用量
    await updateStorageUsage(userId, fileSizeBytes);

    return NextResponse.json({
      url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/upload/${uniqueKey}`,
      fileInfo: {
        name: finalName,
        size: fileSizeBytes,
        sizeMB: Math.ceil(fileSizeBytes / (1024 * 1024))
      }
    });
  } catch (error) {
    console.error("Error uploading file:", error);
    return NextResponse.json(
      { error: "文件上传失败" },
      { status: 500 }
    );
  }
}


